<template>
  <div id="image-recognition">
    <h2>Image Recognition</h2>
    <input type="text" v-model="imageUrl" placeholder="Enter image URL" />
    <button @click="recognizeImage">Recognize</button>
    <div>
      <input type="file" @change="handleFileUpload" />
    </div>
    <p v-if="responseMessage" :class="{'error-message': isError, 'response-message': !isError}">
      {{ responseMessage }}
    </p>
    <div v-if="displayedImage">
      <h3>Image Preview</h3>
      <img :src="displayedImage" alt="Uploaded or URL Image" class="preview-image"/>
    </div>
    <div v-if="plateData.length > 0">
      <h3>Recognized Plate Data</h3>
      <div v-for="(plate, index) in plateData" :key="index" class="plate-info">
        <p><strong>Plate Number:</strong> {{ plate.plateNo }}</p>
        <p><strong>Plate Color:</strong> {{ plate.plateColor }}</p>
        <p><strong>Detection Confidence:</strong> {{ plate.detectConf.toFixed(2) }}</p>
        <p><strong>Color Confidence:</strong> {{ plate.colorConf.toFixed(2) }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: '',
      responseMessage: null,
      isError: false,
      plateData: [],
      displayedImage: null,
    };
  },
  watch: {
    imageUrl(newUrl) {
      this.displayedImage = newUrl;
    }
  },
  methods: {
    async recognizeImage() {
      if (!this.imageUrl) {
        this.responseMessage = 'Please enter an image URL.';
        this.isError = true;
        return;
      }

      this.displayedImage = this.imageUrl;

      try {
        const response = await fetch(
          `http://localhost:8080/recognize?imageUrl=${encodeURIComponent(this.imageUrl)}`,
          {
            method: 'GET',
            headers: {
              Authorization: localStorage.getItem('jwt-token'),
            },
          }
        );

        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const data = await response.json();
        if (data.success && data.data.length > 0) {
          this.plateData = data.data;
          this.responseMessage = null;
          this.isError = false;
        } else {
          this.responseMessage = data.message || 'No plate number recognized.';
          this.isError = true;
          this.plateData = [];
        }
      } catch (error) {
        console.error('There was an error!', error);
        this.responseMessage = 'An error occurred while recognizing the image.';
        this.isError = true;
        this.plateData = [];
      }
    },
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) {
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        this.displayedImage = e.target.result;
      };
      reader.readAsDataURL(file);

      const formData = new FormData();
      formData.append('file', file);

      this.uploadImage(formData);
    },
    async uploadImage(formData) {
      try {
        const response = await fetch('http://localhost:8080/recognize', {
          method: 'POST',
          headers: {
            Authorization: localStorage.getItem('jwt-token'),
          },
          body: formData,
        });

        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const data = await response.json();
        if (data.success && data.data.length > 0) {
          this.plateData = data.data;
          this.responseMessage = null;
          this.isError = false;
        } else {
          this.responseMessage = data.message || 'No plate number recognized.';
          this.isError = true;
          this.plateData = [];
        }
      } catch (error) {
        console.error('There was an error!', error);
        this.responseMessage = 'An error occurred while recognizing the image.';
        this.isError = true;
        this.plateData = [];
      }
    },
  },
};
</script>

<style scoped>
#image-recognition {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
}

input[type="text"], input[type="file"] {
  display: block;
  margin: 10px auto;
  padding: 10px;
  width: 80%;
  box-sizing: border-box;
}

button {
  padding: 10px 20px;
  margin: 10px;
  cursor: pointer;
}

.response-message {
  color: green;
  margin-top: 1rem;
}

.error-message {
  color: red;
  margin-top: 1rem;
}

.preview-image {
  max-width: 100%;
  margin-top: 1rem;
}

.plate-info {
  margin-top: 1.5rem;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
